import {messages,queryCurrencyPrecision} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Button, Input, message, Select, Switch, Divider, DatePicker, InputNumber, Form } from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
import menuRoute from 'routes/menuRoute'
import 'styles/setting/currency-setting/currency-setting-add.scss'
import CurrencySettingService from "containers/setting/currency-setting/currency-setting.service";

class CurrencySettingAdd extends React.Component {
  constructor (props){
    super (props);
    this.state = {
      saving: false,
      currencyOptions: [],
      data: [],
      pageSize: 10,
      params: {},//路由参数
      language: this.props.language.code,
      precision: -1,
      enableAutoUpdate: false,
    };
    this.currencySetting = menuRoute.getRouteItem('currency-setting', 'key');
    this.setOfBooksId = this.props.params.setOfBooksId;
    this.currencyCode = this.props.params.currencyCode;
  }

  componentWillMount () {
    this.getCurrencyName();
    this.getCurrencyDetail();
  }

  //获取当条数据的详情
  getCurrencyDetail = () => {
    const {language} = this.state;
    let param = {
      currencyCode: this.currencyCode,
      setOfBooksId: this.setOfBooksId,
      language,
    };
    CurrencySettingService.getCurrencyDetail(param)
      .then(res => {
        this.setState({
          enableAutoUpdate: res.data.enableAutoUpdate,
        })
      })
  };

  //获取币种名的option
  getCurrencyName = () => {
    const {language,} = this.state;
    let params = {
      setOfBooksId: this.setOfBooksId,
      baseCurrencyCode: this.currencyCode,
      tenantId: this.props.company.tenantId,
      language,
    };
    CurrencySettingService.getCurrencyName(params)
      .then(res => {
          this.setState({
            currencyOptions: res.data.rows
          })
        }
      )
  };

  //选中币种名，选中之后代码随其改变
  onCurrencyNameChange = (value) => {
    const {currencyOptions} = this.state;
    currencyOptions.map(item => {
      if (item.currencyName === value.split('+')[1]) {
        this.props.form.setFieldsValue({currencyCode: item.currencyCode, currencyName: value});
        this.setState({precision: queryCurrencyPrecision(item.currencyCode)})
      }
    })
  };

  //不能选择今天之后
  disabledEndDate = (endValue) => {
    const startValue = new Date();
    if (!endValue || !startValue) {
      return false;
    }
    return endValue.valueOf() > startValue.valueOf();
  };

  //点击保存
  onSave = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      const {language} = this.state;
      if (!err) {
        values.applyDate = values.applyDate.utc().format();
        values.autoUpateRate = false;
        this.setState({saving: true});
        let item = {
          setOfBooksId: this.setOfBooksId,
          baseCurrencyCode: this.currencyCode,
          tenantId: this.props.company.tenantId,
          language,
        };
        let params = Object.assign(values, item);
        CurrencySettingService.onAddNewSave(params)
          .then(res => {
            this.setState({saving: false});
            message.success(messages('setting.key397'/*添加成功*/));
            this.goBack();
          }).catch(() => {
          this.setState({saving: false});
          message.error(messages('setting.key398'/*当前账套尚未启用汇率自动更新服务,请先开启!*/), 3);
          this.goBack();
        })
      }
    })
  };

  goBack = () => {
    this.context.router.push(this.currencySetting.url.replace(":setOfBooksId", this.setOfBooksId))
  };

  render () {
    const { currencyOptions, saving, precision, language, enableAutoUpdate } = this.state;
    const formItemLayout = {
      labelCol: {span: 4},
      wrapperCol: {span: 8, offset: 1},
    };
    const { getFieldDecorator } = this.props.form;
    return (
      <Form className='currency-setting-add' onSubmit={this.onSave}>
        <FormItem {...formItemLayout} label={messages("common.column.status")/*状态*/}>
          {getFieldDecorator('enable', {
            valuePropName: 'checked',
            initialValue: true
          })(
            <Switch />
          )}
        </FormItem>
        <Divider dashed />
        <FormItem labelCol={{span: 4}} wrapperCol={{span: 16, offset: 1}} label={messages('setting.key399'/*币种名*/)}>
          {getFieldDecorator('currencyName', {
            rules: [{
              required: true,
              message: messages('common.please.select')
            }]
          })(
            <div>
              <Select onSelect={this.onCurrencyNameChange}
                      placeholder={messages("common.please.select")/*请选择币种名*/}
                      getPopupContainer={triggerNode => triggerNode.parentNode}
                      showSearch={true}
                      style={{display:"inlineBlock",width:'50%'}}
                      filterOption={(inputValue, option) => option.props.children.toLowerCase().indexOf(inputValue.toLowerCase()) > -1}>
                {currencyOptions.map((item, index) => {
                  return <Option key={`${item.currencyCode}+${item.currencyName}`}>
                    {language.toLowerCase() === 'en' ? item.currencyCode : `${item.currencyCode} ${item.currencyName}`}</Option>
                })}
              </Select>
              {
                precision > -1 && (
                  <span style={{marginLeft:'10px'}}>{messages('setting.key1485')/*币种精度*/}:{precision}</span>
                )
              }
            </div>
          )}
        </FormItem>
        <FormItem {...formItemLayout} label={messages('setting.key400'/*代码*/)}>
          {getFieldDecorator('currencyCode', {
            rules: [{
              required: true,
              message: messages('common.please.enter')
            }]
          })(
            <Input disabled/>
          )}
        </FormItem>
        <FormItem {...formItemLayout} label={messages('setting.key401'/*汇率生效日期*/)}>
          {getFieldDecorator('applyDate', {
            rules: [{
              required: true,
              message: messages('common.please.select')
            }]
          })(
            <DatePicker disabledDate={this.disabledEndDate}
                        style={{ width: '100%' }}
                        allowClear={false}/>
          )}
        </FormItem>
        <FormItem {...formItemLayout} label={messages('setting.key402'/*生效汇率*/)}>
          {getFieldDecorator('rate', {
            rules: [{
              required: true,
              message: messages('setting.key403'/*生效汇率必须为大于0的数字*/) /*生效汇率必须为大于0的数字*/,
              validator: (personObj,value, cb) => {
                if(value === "" || value === undefined || value === null){
                  cb(false);
                };
                if(typeof (value) !== 'number' ||  value <= 0){
                  cb(false);
                }else {
                  cb();
                }
              },
            }
            ]
          })(
            <InputNumber min={0.01}  precision={2} step={0.01} style={{ width: '100%' }}/>
          )}
        </FormItem>

        <FormItem {...formItemLayout} label={messages('setting.key404'/*启用自动汇率:*/)}>
          {getFieldDecorator('enableAutoUpdate', {
            valuePropName: 'checked',
            initialValue: enableAutoUpdate
          })(
            <Switch disabled={!enableAutoUpdate}/>
          )}
        </FormItem>

        <FormItem {...formItemLayout} wrapperCol={{ offset: 5 }}>
          <Button type='primary' htmlType="submit" loading={saving}>{messages("common.save")/*保存*/}</Button>
          <Button onClick={this.goBack} style={{ marginLeft: 15 }}>
            {messages("common.back")/*返回*/}
          </Button>
        </FormItem>
      </Form>
    )
  }
}

CurrencySettingAdd.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    language: state.main.language,
    tenantMode: state.main.tenantMode,
    company: state.login.company,
  }
}


const WrappedCurrencySettingAdd = Form.create()(CurrencySettingAdd);
export default connect(mapStateToProps)(WrappedCurrencySettingAdd);
